package com.hps.demo.registry;

import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author heps
 * @since 2020/8/15
 */
@Slf4j
@Configuration
public class ServiceRegistry {

  @Value("${registry.address}")
  private String registryAddress;

  private static final String ZK_REGISTRY_PATH = "/rpc";

  public void register(String data) {
    if (StringUtils.isNotBlank(data)) {
      ZkClient client = connectServer();
      if (Objects.nonNull(client)) {
        addRootNode(client);
        createNode(client, data);
      }
    }
  }

  private ZkClient connectServer() {
    return new ZkClient(registryAddress, 20000, 20000);
  }

  private void addRootNode(ZkClient client) {
    boolean exists = client.exists(ZK_REGISTRY_PATH);
    if (!exists) {
      client.createPersistent(ZK_REGISTRY_PATH);
      log.info("创建zookeeper主节点 {}", ZK_REGISTRY_PATH);
    }
  }

  private void createNode(ZkClient client, String data) {
    String path = client.create(ZK_REGISTRY_PATH + "/provider", data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
    log.info("创建zookeeper数据节点 ({} => {})", path, data);
  }
}
